<template>
  <!-- 自定义导航栏 -->
  <CustomNavbar></CustomNavbar>
  <template v-if="memberStore.profile">
    <!-- 浮窗按钮 -->
    <view v-if="isShowButton && selectedCartListCount > 0" class="float-button" @tap="openPopup('address')">
      <uni-badge :text="selectedCartListCount" absolute="rightTop" class="uni-badge-left-margin" size="small">
        <image class="location-image" src="@/static/tabs/cart_selected.png"></image>
      </uni-badge>
    </view>
    <view class="viewport" :style="{paddingBottom: tabBarHeights+'px'}">
      <!-- 分类 -->
      <!-- 上侧：一级分类 -->
      <view class="categoriestap">
        <view class="today">{{ pstime }}</view>
        <view class="rightime">
          <span>截单时间：</span>
          <span> {{ mytime }} </span>
        </view>
      </view>
      <!-- 右侧：二级分类 -->
      <scroll-view class="secondary" enable-back-to-top scroll-y>
        <!-- 商品列表 -->
        <!-- 商品信息 -->
        <view v-for="goods in mealList" :key="goods.id" class="cart-swipe">
          <view class="goods">
            <view class="navigator">
              <image :src="goods.picture" @tap="handleTap(goods)" class="picture" mode="aspectFill" lazy-load="true">
              </image>
              <view class="meta">
                <view class="name ellipsis">{{ goods.name }}</view>
                <view class="attrsText ellipsis">配菜：{{goods.mealdesc}}</view>
                <view class="attrsText ellipsis">口味：{{goods.taste}}</view>
                <view class="prices">
                  <view class="pay-price symbol">
                    <span>¥</span>
                    <span>{{ priceWithDiscount(goods.price, goods.discount)  }}</span>
                  </view>
                  <view class="price symbol">{{priceTwoDecimal(goods.price) }}</view>
                </view>
              </view>
            </view>
            <!-- 商品数量 -->
            <view class="count">
              <button class="mini-btn" type="primary" :disabled="goods.count<=0" @tap="subgoods(goods)"
                size="mini">-</button>
              <view style="width:130rpx;text-align: center;">{{goods.count}}</view>
              <button class="mini-btn" type="primary" @tap="addgoods(goods)" size="mini">+</button>
              <!-- <vk-data-input-number-box v-model="goods.count" :index="goods.id" :max="goods.stock" :min="0" /> -->
            </view>
          </view>
        </view>
        <view class="goods">
          <text class="goodsFoot">
            没有更多数据了~
          </text>
        </view>
      </scroll-view>
    </view>
  </template>
  <!-- 未登录: 提示登录 -->
  <view v-else class="login-blank">
    <text class="text">登录后可查看购物车中的商品</text>
    <navigator hover-class="none" url="/pages/login/login">
      <button class="button">去登录</button>
    </navigator>
  </view>
  <!-- uni-ui 弹出层 -->
  <uni-popup ref="popup" background-color="#fff" type="bottom" @change="change" @maskClick="maskClick">
    <scroll-view v-if="cartList.length > 0" class="popup-scroll" enable-back-to-top scroll-y>
      <!-- 商品列表 -->
      <!-- 商品信息 -->
      <view v-for="goods in mealList" :key="goods.id" class="cart-swipe">
        <view v-show="goods.count != 0" class="goods">
          <navigator class="navigator">
            <image :src="goods.picture" class="picture" mode="aspectFill" lazy-load="true"></image>
            <view class="meta">
              <view class="name ellipsis">{{ goods.name }}</view>
              <view class="attrsText ellipsis">配菜：{{goods.mealdesc}}</view>
              <view class="attrsText ellipsis">口味：{{goods.taste}}</view>
              <view class="prices">
                <view class="pay-price symbol">
                  <span>¥</span>
                  <span>{{ priceWithDiscount(goods.price, goods.discount) }}</span>
                </view>
                <view class="price symbol">{{ priceTwoDecimal(goods.price)}}</view>
              </view>
            </view>
          </navigator>
          <!-- 商品数量 -->
          <view class="count">
            <button class="mini-btn" type="primary" :disabled="goods.count<=0" @tap="subgoods(goods)"
              size="mini">-</button>
            <view style="width:130rpx;text-align: center;">{{goods.count}}</view>
            <button class="mini-btn" type="primary" @tap="addgoods(goods)" size="mini">+</button>
            <!-- <vk-data-input-number-box v-model="goods.count" :index="goods.id" :max="goods.stock" :min="0" /> -->
          </view>
        </view>
      </view>
    </scroll-view>
    <!-- 吸底工具栏 -->
    <view class="toolbar">
      <text class="text">合计:</text>
      <view class="prices">
        <text class="amount">{{ selectedCartListMoneyWithDiscount }}</text>
        <text class="price">¥</text>
        <text class="price symbol">{{ selectedCartListMoney }}</text>
      </view>
      <view class="button-grounp">
        <view :class="{ disabled: selectedCartListCount === 0 }" class="button payment-button" @tap="gotoPayment">
          去结算({{ selectedCartListCount }})
        </view>
      </view>
    </view>
  </uni-popup>
</template>
<script lang="ts" setup>
  import { getMealTypeAPI } from "@/services/category";
  import { getMealListAPI } from "@/services/goods";
  import type { CategoryTopItem } from "@/types/category";
  import { onLoad, onUnload } from "@dcloudio/uni-app";
  import { computed, ref, watch } from "vue";
  import CustomNavbar from "./components/CustomNavbar.vue";
  import { useMemberStore } from "@/stores";
  import { useCartStore } from "@/stores/cart";
  import { storeToRefs } from "pinia";
  import { priceWithDiscount, priceTwoDecimal } from "@/utils/meal";
  import { log } from "console";
  import { onReady, onShow } from '@dcloudio/uni-app'
  // 获取会员Store
  const memberStore = useMemberStore();

  // uni-ui 弹出层组件 ref
  const popup = ref<{
    open : (type ?: UniHelper.UniPopupType) => void;
    close : () => void;
  }>();

  // 弹出层条件渲染
  const popupName = ref<"address" | "service">();
  const openPopup = (name : typeof popupName.value) => {
    // 修改弹出层名称
    popupName.value = name;
    popup.value?.open();
  };

  const handleTap = (row : any) => {
    uni.previewImage({
      urls: [row.picture], //需要预览的图片http链接列表，多张的时候，url直接写在后面就行了
      current: '1', // 当前显示图片的http链接，默认是第一个
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) { },
    })
  };

  // 弹出层状态变化
  // 是否显示浮窗
  const isShowButton = ref(true);
  const change : UniHelper.UniPopupOnChange = (ev) => {
    isShowButton.value = !ev.show;
  };

  //点击弹出层的遮罩层触发
  const maskClick = () => { };

  // 获取餐品分类数据
  const mytime = ref("");
  const pstime = ref<string>(formatDate(new Date()));

  const mealTypeList = ref<CategoryTopItem[]>([]);
  const activeIndex = ref(0);
  const getJieDanData = async () => {
    const res = await getMealTypeAPI();
    mealTypeList.value = res.result;
    mytime.value = res.result[0].hour + ":" + res.result[0].minute;
  };

  // 是否数据加载完毕
  const isFinish = ref(false);
  // 切换套餐类型
  const currentMealType = ref("早餐");
  const changeTime = (index : number, type : string) => {
    // 模态弹窗
    uni.showModal({
      content: "切换菜单将清空当前购物车，是否继续？",
      success: (res) => {
        if (res.confirm) {
          activeIndex.value = index;
          currentMealType.value = type;
          mytime.value =
            "截单时间: " +
            mealTypeList.value[index].hour +
            ":" +
            mealTypeList.value[index].minute;
          getMealList();
        }
      },
    });
  };

  const getCategoryTopData = async () => {
    //const res = await getCategoryTopAPI()
  };
  // 获取套餐列表
  const cartStore = useCartStore();
  const {
    cartList,
    mealList,
    selectedCartListMoney,
    selectedCartListMoneyWithDiscount,
  } = storeToRefs(cartStore);

  const getMealList = async () => {
    const res = await getMealListAPI(currentMealType.value, memberStore.profile!.addressid);
    mealList.value = res.result;
  };

  onShow(async () => {
    const res = await getMealListAPI(currentMealType.value, memberStore.profile!.addressid);
    mealList.value = res.result;

  })

  // 当更改配送点后重新获取套餐列表
  const { profile } = storeToRefs(memberStore);
  watch(
    () => profile.value?.addressid,
    async (newValue, oldValue) => {
      if (newValue !== oldValue) {
        await getMealList();
      }
    }
  );

  const addgoods = (row : any) => {
    mealList.value.forEach((item) => {
      if (item.id == row.id) {
        item.count++
      }
    })
  }

  const subgoods = (row : any) => {
    mealList.value.forEach((item) => {
      if (item.id == row.id) {
        item.count--
      }
    })
  }



  // 计算选中总件数
  const selectedCartListCount = computed(() => {
    return cartList.value.reduce((sum, item) => sum + item.count!, 0);
  });

  // 结算按钮
  const gotoPayment = () => {
    if (selectedCartListCount.value === 0) {
      uni.showToast({
        icon: "none",
        title: "请选择商品",
      });
    } else if (mytime.value !== "" && compareDate(`${pstime.value} ${mytime.value}`)) {
      uni.showModal({
        title: "当前餐品已过了截单时间，您可以选择预定第二天的午餐",
        success({ confirm }) {
          if (confirm) {
            const date = new Date();
            date.setDate(date.getDate() + 1);
            pstime.value = formatDate(date);
            uni.navigateTo({ url: `/pagesOrder/create/create?pstime=${pstime.value}` });
          }
        },
      });
    } else {
      uni.navigateTo({ url: `/pagesOrder/create/create?pstime=${pstime.value}` });
    }
  };

  const tabBarHeights = ref(0)

  // 页面加载
  onLoad(async () => {
    // 获取系统信息
    const systemInfo = uni.getSystemInfoSync()
    // 计算TabBar高度
    tabBarHeights.value = systemInfo.screenHeight - systemInfo.windowHeight + 50;
    await Promise.all([getJieDanData(), getCategoryTopData()]);
    isFinish.value = true;
    if (cartList.value.length === 0) {
      getMealList();
    }
    uni.$on("refreshMealList", async () => {
      await getMealList();
    });
    uni.$on("closeCart", () => {
      popup.value?.close();
    });
  });

  onUnload(() => {
    uni.$off("closeCart");
    uni.$off("refreshMealList");
  });
  //

  // 将 `YYYY-MM-DD H:mm` 形式的字符串与当前时间进行比较
  function compareDate(dateString : string) : boolean {

    // 1. 将 `YYYY-MM-DD H:mm` 格式的字符串转换为 Date 对象
    const dateParts = dateString.split(" "); // 分割日期和时间
    const [year, month, day] = dateParts[0].split("-").map(Number);
    const [hour, minute] = dateParts[1].split(":").map(Number);

    // 创建 Date 对象
    const targetDate = new Date(year, month - 1, day, hour, minute);

    // 2. 获取当前时间的 Date 对象
    const currentDate = new Date();

    // 3. 比较当前时间与目标时间
    return currentDate.getTime() > targetDate.getTime(); // 如果当前时间晚于目标时间，则返回 true
  }

  // 将日期对象格式化为 "YYYY-MM-DD" 格式
  function formatDate(date : Date) {
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, "0");
    const day = date.getDate().toString().padStart(2, "0");
    return `${year}-${month}-${day}`;
  }
</script>
<style lang="scss">
  @import "./styles/category.scss";

  .prices {
    display: flex;
    align-items: baseline;
    margin-top: 6rpx;
    font-size: 28rpx;

    .pay-price {
      margin-right: 10rpx;
      color: #cf4444;
    }

    .price {
      font-size: 24rpx;
      color: #999;
      text-decoration: line-through;
    }
  }

  .goodsFoot {
    height: 90rpx;
    text-align: center;
    color: #999;
    width: 750rpx;
  }
</style>
